import { createStore } from "vuex";
import { App } from "vue";
import { getUserInfiApi } from "../request/api";
import { reject } from "lodash";

interface menuItem {
  parentId: number;
  id: number;
  children?: menuItem[];
}

interface State {
  menus: menuItem[];
  userInfo: {};
}
type newMenusType = {
  [key: number]: menuItem;
};

const store = createStore<State>({
  state() {
    return {
      menus: [],
      userInfo: {},
    };
  },
  getters: {
    getNewMenus(state) {
      let firstMenus: newMenusType = {}; // 一级菜单
      state.menus.forEach((item, index) => {
        if (item.parentId === 0) {
          // 如果parentId为0，那么就是一级菜单，存到对象中去
          firstMenus[item.id] = JSON.parse(JSON.stringify(item));
        } else {
          // 否则是二级菜单
          firstMenus[item.parentId] = firstMenus[item.parentId] || {};
          firstMenus[item.parentId].children =
            firstMenus[item.parentId].children || [];
          firstMenus[item.parentId].children?.push(item);
        }
      });

      return firstMenus;
    },
  },
  mutations: {
    updateMenus(state, menus) {
      state.menus = menus;
    },
    updateUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
  },
  actions: {
    getMenus(context) {
      // 发送网络请求获取数据
      return new Promise((resolve, reject) => {
        getUserInfiApi().then(res => {
          if (res.code === 200) {
            context.commit("updateMenus", res.data.menus);
            let userObj = {
              icon: res.data.icon,
              roles: res.data.roles,
              username: res.data.username,
            };
            context.commit("updateUserInfo", userObj);
            resolve(res);
          }
        });
      });
    },
  },
  modules: {},
});

export const initStore = (app: App<Element>) => {
  app.use(store);
};

// 用于在ts或js文件中使用store的数据
export default store;
